package com.zk.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zk.entities.SysOrganization;
import com.zk.service.OrgServcice;

@Controller
public class OrgController {

	@Autowired
	private OrgServcice orgService;
	
	/**
	 * 新增组织机构
	 * @param sysOrganization
	 * @return
	 */
	@RequestMapping("/add_org")
	public String add_org(SysOrganization sysOrganization) {
		orgService.add_org(sysOrganization);
		return "redirect:/get_org_list.do";
	}
	
	@RequestMapping("/get_org_list")
	@ResponseBody
	public List<SysOrganization> get_org_list(){
		//使用Map集合整合菜单之间的关系
		List<SysOrganization> orgList = new ArrayList<SysOrganization>();
		//查询数据库的所有数据
		List<SysOrganization> dbOrgs = orgService.get_org_list();
		
		Map<Integer, SysOrganization> orgMap = new HashMap<Integer, SysOrganization>();
		//循环遍历从数据库查询到的每一条数据，并放进Map集合中
		for (SysOrganization org : dbOrgs) {
			orgMap.put(org.getId(), org);
		}
		//循环遍历每一个数据
		for (SysOrganization org : dbOrgs) {
			//子菜单，先暂时吧每个节点当成子节点
			SysOrganization child = org;
			//如果子节点的Pid为0,代表它的上一级节点是根节点
			if (child.getParentId() == 0) {
				//把当前节点放到根节点后，该节点id为1
				orgList.add(org);
			}else {
				//父菜单，通过子节点的pid获取父节点的id，再通过父节点的id获取父节点，通过子节点查找父节点
				SysOrganization parent = orgMap.get(child.getParentId());
				//组合父子菜单的关系
				parent.getChildren().add(child);
			}
		}
		return orgList;
	}
	

	/**
	 * 修改组织机构
	 * @param sysOrganization
	 * @return
	 */
	@RequestMapping("edit_org")
	public String edit_org(SysOrganization sysOrganization) {
		orgService.edit_org(sysOrganization);
		return "redirect:/get_org_list.do";
	}
	
	@RequestMapping("goto_edit_org")
	@ResponseBody
	public SysOrganization goto_edit_org(Integer id) {
		return orgService.get_org_by_id(id);
	}
	/**
	 * 删除组织机构
	 * @param sysOrganization
	 * @return
	 */
	@RequestMapping("remove_org")
	@ResponseBody
	public boolean remove_org(Integer id) {
		int result = orgService.remove_org(id);
		
		if (result == 0) {
			return false;
		}else {
			return true;
		}
	}
}
